package com.kamistoat.meimeistore.modulessystem.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


import com.kamistoat.meimeistore.apisystem.domain.SysPost;
import com.kamistoat.meimeistore.apisystem.entity.SysPostEntity;
import com.kamistoat.meimeistore.commoncore.utils.poi.ExcelUtil;
import com.kamistoat.meimeistore.commoncore.web.controller.BaseController;
import com.kamistoat.meimeistore.commoncore.web.domain.AjaxResult;
import com.kamistoat.meimeistore.commoncore.web.page.TableDataInfo;
import com.kamistoat.meimeistore.commonlog.annotation.Log;
import com.kamistoat.meimeistore.commonlog.enums.BusinessType;
import com.kamistoat.meimeistore.commonsecurity.annotation.RequiresPermissions;
import com.kamistoat.meimeistore.commonsecurity.utils.SecurityUtils;
import com.kamistoat.meimeistore.modulessystem.service.SysPostService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;


/**
 * 岗位信息表
 *
 * @author kamistoat
 * @email linjianshanke@163.com
 * @date 2022-08-09 10:34:46
 */
@RestController
@RequestMapping("/post")
public class SysPostController extends BaseController {
    @Autowired
    private SysPostService sysPostService;

    /**
     * 获取岗位列表.
     * 疑问。这里的权限没有设置。直接是所有人都可以查看所有岗位
     */
    @RequiresPermissions("system:post:list")
    @GetMapping("/list")
    public TableDataInfo list(SysPost sysPost) {
        startPage();
        List<SysPostEntity> sysPostEntityList = sysPostService.selectPostList(sysPost);
        return getDataTable(entity2Vo(sysPostEntityList));
    }

    /**
     * 导出岗位
     */
    @Log(title = "岗位管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:post:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysPost sysPost) {
        List<SysPostEntity> sysPostEntityList = sysPostService.selectPostList(sysPost);
        ExcelUtil<SysPost> util = new ExcelUtil<SysPost>(SysPost.class);
        util.exportExcel(response, entity2Vo(sysPostEntityList), "岗位数据");
    }

    /**
     * 根据岗位编号获取详细信息
     */
    @RequiresPermissions("system:post:query")
    @GetMapping(value = "/{postId}")
    public AjaxResult getInfo(@PathVariable Long postId) {
        return AjaxResult.success(entity2Vo(sysPostService.selectPostByPostId(postId)));
    }

    /**
     * 新增岗位
     */
    @RequiresPermissions("system:post:add")
    @Log(title = "岗位管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysPost post) {
        if (sysPostService.checkPostNameUnique(post)) {
            return AjaxResult.error("新增岗位'" + post.getPostName() + "'失败，岗位名称已存在");
        } else if (sysPostService.checkPostCodeUnique(post)) {
            return AjaxResult.error("新增岗位'" + post.getPostName() + "'失败，岗位编码已存在");
        }
        post.setCreateBy(SecurityUtils.getUserName());
        return toAjax(sysPostService.save(vo2Entity(post)));
    }

    /**
     * 修改岗位.
     */
    @RequiresPermissions("system:post:edit")
    @Log(title = "岗位管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysPost sysPost) {
        if (!SecurityUtils.curLoginUserIsAdmin() && !SecurityUtils.getLoginUser().getPostIds().contains(sysPost.getPostId())) {
            return AjaxResult.error("修改岗位'" + sysPost.getPostName() + "'失败，非管理员用户无权修改除自身部门之外的部门");
        }
        if (sysPostService.checkPostNameUnique(sysPost)) {
            return AjaxResult.error("修改岗位'" + sysPost.getPostName() + "'失败，岗位名称已存在");
        } else if (sysPostService.checkPostCodeUnique(sysPost)) {
            return AjaxResult.error("修改岗位'" + sysPost.getPostName() + "'失败，岗位编码已存在");
        }
        sysPost.setUpdateBy(SecurityUtils.getUserName());
        return toAjax(sysPostService.updateById(vo2Entity(sysPost)));
    }

    /**
     * 删除岗位
     */
    @RequiresPermissions("system:post:remove")
    @Log(title = "岗位管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{postIds}")
    public AjaxResult remove(@PathVariable Long[] postIds) {
        if (!SecurityUtils.curLoginUserIsAdmin()) {
            ArrayList<Long> allowed = new ArrayList<>(SecurityUtils.getLoginUser().getPostIds());
            for (Long postId : postIds) {
                if (!allowed.contains(postId)) {
                    return AjaxResult.error("修改岗位'" + sysPostService.selectPostByPostId(postId).getPostName() + "'失败，非管理员用户无权修改除自身部门之外的部门");
                }
            }
        }
        return toAjax(sysPostService.removeByIds(Arrays.asList(postIds)));
    }

    /**
     * 无条件获取全部岗位
     */
    @GetMapping("/optionselect")
    public AjaxResult optionselect() {
        List<SysPostEntity> sysPostEntityList = sysPostService.selectPostList(new SysPost());
        return AjaxResult.success(entity2Vo(sysPostEntityList));
    }


    /**
     * Entity 和 Vo类的转换
     */
    private List<SysPost> entity2Vo(List<SysPostEntity> sysPostEntityList) {
        return
                sysPostEntityList.stream().map(sysPostEntity -> {
                    SysPost sysPost = new SysPost();
                    BeanUtils.copyProperties(sysPostEntity, sysPost);
                    return sysPost;
                }).collect(Collectors.toList());
    }

    private SysPost entity2Vo(SysPostEntity sysPostEntity) {
        SysPost sysPost = new SysPost();
        BeanUtils.copyProperties(sysPostEntity, sysPost);
        return sysPost;
    }

    private List<SysPostEntity> vo2Entity(List<SysPost> sysPostList) {
        return
                sysPostList.stream().map(sysPost -> {
                    SysPostEntity sysPostEntity = new SysPostEntity();
                    BeanUtils.copyProperties(sysPost, sysPostEntity);
                    return sysPostEntity;
                }).collect(Collectors.toList());
    }

    private SysPostEntity vo2Entity(SysPost sysPost) {
        SysPostEntity sysPostEntity = new SysPostEntity();
        BeanUtils.copyProperties(sysPost, sysPostEntity);
        return sysPostEntity;
    }

}
